<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {
    public $_data = array();      //所有数据集对象
    public $_params = array();    //所有参数集对象
    public $title = '';
    public $error = 'exception error';           //暂时只返回单一错误信息  
    public $limit = 10;
    public $count = 0;
    public $menu =  '';
    public $uuid = '';
    public $nick_name = "";
    public $avatar = "";
    public $userInfo=[];//用户openid,unionid,session_key
    public $token = "";
    public $ajax_arr= array("status" => 0, "msg" => '系统错误,请联系管理员');
    public function init(){
        $url =  Yii::app()->request->getUrl();
        $urls =  explode("?",$url);
        $uuid  = Tools::_get("uuid","",["prex"=>'/[^\da-z-]/']);

        if(!$uuid){
            $token = Tools::_get("token", "");
            $uuid = StringProcXHelpers::StringProcX($token, "DECODE");
        }
        if(!$uuid){
            if(!in_array($urls[0],Conf::$no_auth_urls)){
                $token =  Tools::_get("color-token", "");
                $user_info = $this->get_user_info($token);
                if(!isset($user_info['user_uuid'])){
                    $this->jout(201);
                }
                $this->check_primary_key_null([$user_info['user_uuid']]);
                $this->nick_name = $user_info["nick_name"];
                $this->avatar = $user_info["portrait"]  ? $user_info["portrait"] : DF_AVATAR ;
                $uuid = $user_info['user_uuid'];
            }
        }
        $this->uuid  = $uuid;
        //布点处理
        if(in_array($urls[0],Conf::$layout_map)){
            $this->layout_map($urls[0]);
        }
    }

    public function get_open_id(){
        $code = Tools::_get("code","");
        if($code){
            $url = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",DXW_WX_APPID,DXW_WX_APP_SEC,$code);
            $result = \Curl::getInstance()->get($url)->getBody();
            $result = json_decode($result,true);
            if(isset($result['openid'])){
                $this->open_id = $result['openid'];
            }else{
                if(strpos($result['errmsg'],'code')>0){
                    $this->jout(208);
                }
            }
        }else{
            $this->jout(208);
        }
    }
    protected function layout_map($url){
        $data["url"] = $url;
        $data["uuid"] = $this->uuid;
        $data["ymd"] = date("Ymd");
        $data["create_date"] = time();
        $data["param"] = $_REQUEST;
        $data["ip"] = $_SERVER["REMOTE_ADDR"];
        RedisMQ::create()->set("layout_map",json_encode($data));

    }
    //不加密返回token  不检测登录
    protected function jo($code,$_data=[],$desc= ""){
        $data["code"] = $code;
        $data["data"] = $_data;
        $data["msg"] =  $desc ? $desc:Conf::get_desc_by_code()[$code];
        $data["token"] =  Tools::_get("token");
        ob_end_clean();
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
        exit();
    }
    public function get_uuid_by_rq(){
        $uuid = Tools::_get("uuid","");
        $this->check_primary_key_null([$uuid]);
        $this->uuid = $uuid;
    }
    //获得当前用户积分
    public function get_score_by_uuid(){
        $token = $this->get_token_by_conf();
        $ice = new ICEService();
        $data["access_token"] = $token;
        $data["user_uuid"] = $this->uuid;
        $re = $ice->dispatch('/xcwscqb/user/integral',$data);
        $list["score"] = 0;
        if(isset($re['integral'])){
            $list["score"] =  ((int)$re['integral'])/100;
        }
        return $list;
    }

    //减积分
    public function reduce_score_by_uuid($order_no,$score,$remark='',$froms=""){
        $token = $this->get_token_by_conf();
        echo "token:{$token}";
        $data["access_token"] = $token;
        $data["user_uuid"] = $this->uuid;
        $data["order_no"] = $order_no;
        $data["amount"] = $score;
        $data["detail"] = $remark;
        $ice = new ICEService();
        $re = $ice->dispatch("/xcwscqb/user/deductionIntegral",[],$data,'POST');
        if(isset($re['tno'])){
            $s['uuid'] = $this->uuid;
            $s['score'] = $score;
            $s['create_date'] = time();
            $s['remark'] = $remark;
            $s['froms'] = $froms;
            $s['from_id'] = $order_no;
            $s['re_no'] = $re['tno'];
            $s['type'] = 2;
            try{
               $s["id"] =  UserScoreModel::create()->add_($s);
                return $s;
            }catch(Exception $e){
                return [];
            }
        }
        return [];
    }
    protected function verify_key(){
        $key = Tools::_get("key");
        if(!$key){
            $this->jout(203);
        }

        $key = StringProcXHelpers::StringProcX($key);
        if($key != TAG_KEY){
            $this->jout(290);
        }
    }
    protected function _make_data($row){
        $data =[];
        foreach($row as $k=>$v){
            $v = str_replace('&acute;',"'",$v);
            $data[$k] = $v ? $v : "";
        }
        return $data;
    }
    protected function get_param(){
        $p = "";
        foreach($_REQUEST AS $k=>$v){
            $p[$k] = $v;
        }
        $str = "";
        foreach($p  as $k=>$v){
            $str .= $str ?  "&{$k}={$v}":"{$k}={$v}";
        }
        return $str;
    }
    protected function getUrl($array=array()){
        $p = null;
        if(count($_REQUEST)){
            foreach($_REQUEST as $key=>$value){
                if($array) {
                    if (in_array($key, $array)) continue;
                }
                $p .="&{$key}={$value}";
            }
        }
        return $p;
    }
    protected function to_success(){
        $this->jout(200);
    }
    public function check_primary_key_null($arr){
        if(is_array($arr)){
            foreach($arr as $item){
                if(!$item){
                    $this->jout(203);
                    exit();
                }
            }
        }else{
            if(!$arr){
                $this->jout(203);
                exit();
            }
        }
    }
    public function check_data_exists($data,$type=""){
        if(!$data){
            $this->jout(206);
            exit();
        }
    }
    //处理查询数据
    protected function fetch($model,$where=" 1=1 ",$order="",$inx = '*'){
        $page = Tools::_get("page",1,array("format"=>"int"));
        $list = $model::create()->fetchAll($where,$page-1,$this->limit,$order,$inx);
        $this->_data["list"] = $list;
    }

    public function get_user_info($token){
        $auth = new ICEService();
        $data["access_token"] =$token;
        $userinfo = $auth->dispatch("/starquth/oauth/user",$data);
        return $userinfo;
    }

    //根据uuid活动用户access_token
    public function get_token_by_conf(){
        $auth = new ICEService();
        $ts = time()*1000;
        $data = [
            'corp_uuid' => CORP_UUID,
            'app_uuid' => ICE_APP_ID,
            'signature' => md5(ICE_APP_ID . $ts . ICE_TOKEN),
            'timestamp' => $ts
        ];
        $access_token = $auth->dispatch("/authms/auth/app",[],$data,"POST");
        return $access_token['accessToken'];

    }
    public function to_error($msg='执行失败',$page='page_c',$e =null){
        if($e instanceof Exception){
            Yii::log( $e->__toString(), CLogger::LEVEL_ERROR, __CLASS__.'::'.__METHOD__.'('.$e->getLine().')' );
        }
        $this->jout(205);
    }

    protected function like($inx,$key=null){
        $key  = $key ? $key : $this->_data["key"];
        return " POSITION('{$key}' IN  {$inx}) ";
    }
    //多条件OR筛选
    protected function likes($options,$key=null){
        $str = "";
        foreach ($options as $v){
            $str .= $str ? " OR {$this->like($v,$key)}":$this->like($v,$key);
        }
        return " ( ".$str." ) ";
    }

    public function jout($code,$_data=[],$desc= ""){
        $data["code"] = $code;
        $data["data"] = $_data;
        $data["msg"] =  $desc ? $desc:Conf::get_desc_by_code()[$code];
        $data["token"] =  StringProcXHelpers::StringProcX($this->uuid,'ENCODE');
        ob_end_clean();
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
        exit();
    }

    //广告列表
    //pos 位置编号
    protected function get_ads($pos){
        $_where = "";
        if('9682cbfb-cd7b-41e1-b6c9-7fad1cc202e7' == $this->uuid){
            $_where =" AND id = 17 ";
        }
        $ct = time();
        $ads =  AdModel::create()->fetchAll(" state ='2' AND '{$ct}' BETWEEN `begin` AND `end` AND pos =  '{$pos}' {$_where}", 0, 6, ' display_order ASC ', "name,cover,url");
        return $ads;
    }

    protected function get_latlng(){
        $latlng = Tools::_get('latlng','');
        $latlng = $latlng ? $latlng : '112.986441,28.188017';
        $ll =  explode(",",$latlng);
        return $this->convert_BD09_To_GCJ02($ll[1],$ll[0]);

    }
    protected function jout_by_sec($code,$_data=[],$desc = ''){
        $data["code"] = $code;
        $data["data"] = $_data;
        $data["msg"] =  $desc ? $desc:Conf::get_desc_by_code()[$code];
        $data["token"] =  $this->token;
        $json_str = json_encode($data,JSON_UNESCAPED_UNICODE);
        ob_end_clean();
        echo StringProcXHelpers::StringProcX($json_str,"ENCODE");
    }

    //计算距离
    protected function get_dis($dis){
        if($dis>=1000){
            $dis =  (ceil(($dis/1000)*100)/100)."Km";
        }elseif($dis<1000 && $dis>=500 ){
            $dis =  ">500m";
        }else{
            $dis =  "<500m";
        }
        return $dis;
    }

    //百度转高德
    private function convert_BD09_To_GCJ02($lat,$lng){
        $x_pi = 3.141592 * 3000.0 / 180.0;
        $x = $lng - 0.0065;
        $y = $lat - 0.006;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $lng = $z * cos($theta);
        $lat = $z * sin($theta);
        return array('lng'=>$lng,'lat'=>$lat);
    }

    //验证图形验证码
    protected function verify_img_code(){
        $key = Tools::_get("key","",["prex"=>'/[^\dA-Za-z-_.]/']);
        $_code = Tools::_get("code","",["format"=>'int']);
        $this->check_primary_key_null([$_code,$key]);

        $code = RedisMQ::create()->set_col(1)->get($key);
        if($code  != $_code){
            $this->jout(360);
        }
    }

    //验证短信验证码
    protected function verify_sms_code($mobile,$code){
        $row = SmsSendModel::create()->fetchOne(" mobile = '{$mobile}' AND code = '{$code}' AND state = '1' ");
        if(!$row){
            $this->jout(223);
        }
        $ct = time();
        if(($ct - $row["create_date"]) > Conf::$verify_code_expire){
            $sms["state"] = 3;
            SmsSendModel::create()->update_($sms," id = '{$row['id']}' ");
            $this->jout(225);
        }
        //成功验证
        $sms["state"] = 2;
        SmsSendModel::create()->update_($sms," id = '{$row['id']}' ");
    }
}
